package org.komarichin.servlets.upload;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.komarichin.beans.IFile;
import org.komarichin.beans.service.IFileService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;

/**
 * <p>
 * &nbsp;
 * </p>
 * User: Michael Komarichin
 * Date: Jan 3, 2010
 * Time: 2:12:53 AM
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 5916304864512858557L;


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        IFileService fileService = (IFileService) appContext.getBean("fileService");
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(200000);
        resp.setContentType("text/plain");
        PrintWriter out = resp.getWriter();
        String command = req.getParameter("command");
        String path = req.getParameter("path");
        Response r = new Response();
        r.setCommand(command);

        try {
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                } else {
                    IFile file = fileService.createBlank();
                    file.setName(item.getName());
                    file.setContentType(item.getContentType());
                    file.setUpdate(new Date());
                    file.setFolder(StringUtils.defaultIfEmpty(path, "/"));
                    try {
                        byte[] c = IOUtils.toByteArray(in);
                        file.setFile(c);
                        file.setLength((long) c.length);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }
                    file = fileService.save(file);
                    ResponseFile f = new ResponseFile();
                    f.wrap(file);
                    r.getFiles().add(f);

                }
            }
        } catch (FileUploadBase.SizeLimitExceededException e) {
            out.println("You exceeded the maximu size ("
                    + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

        resp.getWriter().write(r.toJSON());
    }
}
